package com.chen.recruit.controller;

import com.chen.recruit.common.api.CommonResult;
import com.chen.recruit.common.constants.SysConstants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "验证码管理 CaptchaController")
@RequiredArgsConstructor
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Value("${spring.mail.username}")
    private String sourceEmail;
    private final DefaultKaptcha defaultKaptcha;
    private final JavaMailSender javaMailSender;
    private final RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "生成验证码图片", produces = "image/jpeg")
    @GetMapping
    public void captcha(HttpServletResponse response) throws IOException {
        // 定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, mustrevalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String text = defaultKaptcha.createText();
        redisTemplate.opsForValue().set(SysConstants.CAPTCHA, text, 2, TimeUnit.MINUTES);
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        outputStream.flush();
        outputStream.close();
    }

    @ApiOperation("发送邮箱验证码")
    @PostMapping
    public CommonResult sendEmailCaptcha(@RequestBody Map<String, Object> params) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("重置密码");
        message.setFrom(sourceEmail);
        message.setTo((String) params.get("email"));
        message.setSentDate(new Date());
        String text = defaultKaptcha.createText();
        message.setText("验证码：" + text);
        javaMailSender.send(message);
        redisTemplate.opsForValue().set(SysConstants.EMAIL_CAPTCHA, text, 2, TimeUnit.MINUTES);
        return CommonResult.success();
    }

}
